<template>
  <div id="login" class="login maxwh flex_a_j noselec">
    <div class="dowebok" :class="{active:obj.type === 'register'}">
      <div class="form-container sign-in-container">
        <div class="form_box flex_a_j flex_d_c">
          <h1>{{obj.title}}</h1>
          <!-- 账号密码登录 -->
          <div v-if="navIndex">
            <input
              type="text"
              v-model="incode"
              maxlength="6"
              autocomplete="off"
              placeholder="邀请码"
              @focus="focus"
              @blur="blur"
              v-if="obj.type === 'register'"
            />
            <input
              type="text"
              v-model="phone"
              maxlength="11"
              autocomplete="off"
              placeholder="手机号码"
              @focus="focus"
              @blur="blur"
            />
            <div class="input_box flex_a j_sb" v-if="obj.type !== 'login'">
              <input
                type="text"
                v-model="qrcode"
                maxlength="6"
                autocomplete="off"
                @focus="focus"
                @blur="blur"
                placeholder="验证码"
              />
              <button class="flex_a_j" :class="{'active':codeY}" :disabled="codeY" @click="getQRcode">{{num}}</button>
            </div>
            <input
              type="password"
              v-model="password"
              maxlength="20"
              autocomplete="off"
              placeholder="密码"
              @focus="focus"
              @blur="blur"
              v-if="obj.type === 'login'"
              @keydown.enter="submit"
            />
            <input
              type="password"
              v-model="password"
              maxlength="20"
              autocomplete="off"
              placeholder="密码"
              @focus="focus"
              @blur="blur"
              v-if="obj.type === 'register'"
            />
            <input
              type="text"
              v-model="nickname"
              maxlength="8"
              autocomplete="off"
              placeholder="昵称"
              @focus="focus"
              @blur="blur"
              v-if="obj.type === 'register'"
            />
            <p class="c_page flex_a" v-if="obj.type === 'login'">
              <van-checkbox v-model="checked" icon-size="18px" checked-color="#07c160" @change="remember">记住密码</van-checkbox>
            </p>
          </div>
          <!-- 短信登录 -->
          <div v-else>
            <input
              type="text"
              v-model="phone"
              maxlength="11"
              autocomplete="off"
              placeholder="手机号码"
              @focus="focus"
              @blur="blur"
            />
            <div class="input_box flex_a j_sb">
              <input
                type="text"
                v-model="qrcode"
                maxlength="6"
                autocomplete="off"
                @focus="focus"
                @blur="blur"
                placeholder="验证码"
              />
              <button class="flex_a_j" :class="{'active':codeY}" :disabled="codeY" @click="getQRcode">{{num}}</button>
            </div>
          </div>
          <p class="c_page flex_a j_sb">
            <span @click="toForgot" v-if="obj.type !== 'forgot'">找回密码</span>
            <span @click="toRegister" v-if="obj.type !== 'register'">立即注册</span>
            <span @click="toLogin" v-if="obj.type !== 'login'">立即登录</span>
          </p>
          <button class="send_btn" @click="submit">{{obj.submit}}</button>
          <p class="login_msg flex_a" @click="loginNavHandle">
            <van-icon name="warning-o" color="#ffba33" size="18" />
            <span>短信登录</span>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import secret from '@/assets/js/secret.js';
import { mapActions, mapState } from 'vuex';
export default {
  data() {
    return {
      navIndex: true,
      incode: '',
      phone: '',
      password: '',
      nickname: '',
      qrcode: '',
      num: '获取验证码',
      checked: true,
      codeY: false,
      timer: null,
    };
  },
  computed: {
    ...mapState(['obj', 'config']),
  },
  mounted() {
    let pwd = localStorage.getItem('dp31nrdnjs');
    if (pwd) {
      this.checked = true;
      let decrypt = secret.decrypt(pwd, 'jiamipassword');
      this.phone = decrypt.user;
      this.password = decrypt.password;
    } else {
      this.checked = false;
      this.phone = '';
      this.password = '';
    }
    if (location.hostname === 'localhost') {
      this.phone = '13543212345';
      this.password = '123456';
    }
    this.RemoveMemory(['dp31nrdnjs']);
    this.$store.dispatch('ON_USERINFO', {});
  },
  beforeDestroy() {
    this.timer = null;
    clearInterval(this.timer);
  },
  methods: {
    ...mapActions([
      'ON_SETOBJ',
      'ON_LOGIN',
      'ON_REGISTER',
      'ON_STORAGETIMES',
      'ON_RECOVERPWD',
    ]),
    loginNavHandle() {
      this.navIndex = !this.navIndex;
    },
    // 记住密码
    remember(e) {
      this.checked = e;
      if (this.checked === false) {
        localStorage.removeItem('dp31nrdnjs');
      }
    },
    //清除特定localStorage
    RemoveMemory(keys) {
      let localStorageArr = [];
      for (let i = 0; i < localStorage.length; i++) {
        localStorageArr.push(localStorage.key(i));
      }
      localStorageArr.map((key) => {
        if (keys.indexOf(key) === -1) {
          localStorage.removeItem(key);
        }
      });
    },
    focus: function () {
      if (/(Android)/i.test(navigator.userAgent)) {
        const test = document.querySelector('.dowebok');
        document.body.style.height = window.screen.availHeight + 'px';
        if (document.activeElement.tagName == 'INPUT') {
          setTimeout(() => {
            test.scrollIntoView(true);
          }, 10);
        }
      }
    },
    blur: function () {
      const test = document.querySelector('.dowebok');
      document.body.style.height = '100%';
      test.scrollIntoViewIfNeeded(true);
    },
    // 登录
    login: function () {
      if (this.navIndex) {
        this.loginPwd();
      }
    },
    // 账号密码登录
    loginPwd() {
      this.$api('index/login/userLogin', {
        mobile: this.phone,
        password: this.password,
      }).then((res) => {
        if (res.errorcode === 200) {
          this.ON_LOGIN(res);
          this.ON_STORAGETIMES(0.5);
          var data = { user: this.phone, password: this.password };
          let encrypt = secret.encrypt(data, 'jiamipassword');
          if (this.checked) {
            localStorage.setItem('dp31nrdnjs', encrypt);
          }
        }
      });
    },
    // 注册
    register: function () {
      this.$api('index/users/register', {
        incode: this.incode,
        mobile: this.phone,
        password: this.password,
        code: this.qrcode,
        nikename: this.nickname,
      }).then((res) => {
        if (res.errorcode === 200) {
          this.ON_REGISTER(res);
        }
      });
    },
    // 找回密码
    forgot: function () {
      this.$api('index/users/recoverpwd', {
        mobile: this.phone,
        code: this.qrcode,
      }).then((res) => {
        if (res.errorcode === 200) {
          this.ON_RECOVERPWD(res.msg);
        }
      });
    },
    // 获取验证码
    getQRcode: function () {
      let type = 1;
      let n = 60;
      let url = '';
      if (this.navIndex) {
        url = 'index/users/getVerifyCode';
      } else {
        url = 'index/users/getVerifyLoginCode';
      }
      if (this.obj.type === 'register') {
        type = 1;
      } else if (this.obj.type === 'forgot') {
        type = 2;
      }
      if (this.phone) {
        this.codeY = true;
        if (this.codeY) {
          this.timer = setInterval(() => {
            n--;
            this.num = n + ' s';
            if (n <= 0) {
              clearInterval(this.timer);
              this.codeY = false;
              this.num = '获取验证码';
            }
          }, 1000);
        }
        this.$api(url, {
          mobile: this.phone,
          type: type,
        }).then((res) => {
          if (res.errorcode === 200) {
            this.$toast({ message: res.msg, duration: 2200 });
          }
        });
      } else {
        this.$toast('请输入正确的手机号码！');
      }
    },
    // 表单验证
    submit: function () {
      const phoneReg = /^1\d{10}$/;
      const pwdReg = /^[A-Za-z0-9]{6,20}$/;
      const uPattern = /^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]|[a-zA-Z0-9_]){2,8}$/;
      if (!this.navIndex) {
        if (!phoneReg.test(this.phone)) {
          this.$toast('请输入正确的手机号码！');
        } else if (!this.qrcode) {
          this.$toast('验证码不正确');
        } else {
          this.login();
        }
      } else {
        switch (this.obj.type) {
          case 'login':
            if (!phoneReg.test(this.phone)) {
              this.$toast('请输入正确的手机号码！');
            } else if (!pwdReg.test(this.password)) {
              this.$toast('密码为6-20位,由字母、数字组成！');
            } else {
              this.login();
            }
            break;
          case 'register':
            if (!phoneReg.test(this.phone)) {
              this.$toast('请输入正确的手机号码！');
            } else if (!this.qrcode) {
              this.$toast('验证码不正确');
            } else if (!pwdReg.test(this.password)) {
              this.$toast('密码为6-20位,由字母、数字组成！');
            } else if (!uPattern.test(this.nickname)) {
              this.$toast('昵称由2-8位，字母、数字、汉字组成！');
            } else if (this.incode) {
              if (this.incode.length > 0 || this.incode.length < 7) {
                this.register();
              } else {
                this.$toast('请输入正确的邀请码！');
              }
            } else {
              this.register();
            }
            break;
          case 'forgot':
            if (!phoneReg.test(this.phone)) {
              this.$toast('请输入正确的手机号码！');
            } else if (!this.qrcode) {
              this.$toast('验证码不正确');
            } else {
              this.forgot();
            }
            break;
          default:
            break;
        }
      }
    },
    toLogin: function () {
      let obj = {
        title: '登录',
        type: 'login',
        submit: '登录',
      };
      this.phone = '';
      this.password = '';
      this.qrcode = '';
      this.nickname = '';
      this.ON_SETOBJ(obj);
    },
    toRegister: function () {
      let obj = {
        title: '注册',
        type: 'register',
        submit: '注册',
      };
      this.phone = '';
      this.password = '';
      this.qrcode = '';
      this.nickname = '';
      this.ON_SETOBJ(obj);
    },
    toForgot: function () {
      let obj = {
        title: '找回密码',
        type: 'forgot',
        submit: '确认',
      };
      this.phone = '';
      this.password = '';
      this.qrcode = '';
      this.nickname = '';
      this.ON_SETOBJ(obj);
    },
  },
  components: {},
};
</script>
<style lang="less" scoped>
.login {
  background: #f6f5f7;
  font-family: Avenir-Heavy, PingFang SC, Helvetica Neue, Arial, sans-serif;
}

.login_msg {
  position: absolute;
  bottom: 0px;
  right: 0;
  font-size: 12px;
  color: #666;
  padding: 0 16px;
  line-height: 36px;
  cursor: pointer;
  & span {
    margin-left: 4px;
  }
}

.dowebok {
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 12px 0 rgba(0, 0, 0, 0.2);
  position: relative;
  overflow: hidden;
  width: 320px;
  min-height: 420px;
  max-height: 480px;
}

.dowebok.active {
  padding: 20px 0;
}

.form-container {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  height: 100%;
  width: 100%;
  transition: all 0.6s ease-in-out;
  & .form_box {
    position: relative;
    background: #fff;
    padding: 0px 50px;
    height: 100%;
    text-align: center;
    h1 {
      font-weight: bold;
      margin: 0 0 30px;
    }
    & input {
      background: #eee;
      border: none;
      padding: 12px 15px;
      margin: 8px 0;
      width: 100%;
      outline: none;
    }
    .input_box {
      width: 100%;
      height: 40px;
      background: #eee;
      padding: 0 15px;
      margin: 8px 0;
      & input {
        background: #eee;
        border: none;
        padding: 12px 0px;
        margin: 0;
        width: 66%;
        outline: none;
      }
      & button {
        border-radius: 4px;
        font-size: 12px;
        width: 34%;
        height: 70%;
        color: #ffffff;
        background: #ff4b2b;
      }
      & button.active {
        background: #707070;
      }
    }
    .c_page {
      width: 100%;
      font-size: 12px;
      margin-bottom: 20px;
      & span {
        line-height: 1.5;
        cursor: pointer;
      }
    }
    .send_btn {
      border-radius: 20px;
      border: 1px solid #ff4b2b;
      background: #ff4b2b;
      color: #fff;
      font-size: 14px;
      font-weight: bold;
      padding: 10px 60px;
      letter-spacing: 1px;
      text-transform: uppercase;
      transition: transform 80ms ease-in;
      cursor: pointer;
    }
  }
}
</style>